package com.healthy_software.service.Impl;

import com.healthy_software.constant.MessageConstant;
import com.healthy_software.dto.GoalDTO;
import com.healthy_software.dto.GoalDetailDTO;
import com.healthy_software.dto.SetGoalRequestDTO;
import com.healthy_software.entity.Goal;
import com.healthy_software.entity.GoalDetail;
import com.healthy_software.mapper.GoalDetailsMapper;
import com.healthy_software.mapper.GoalMapper;
import com.healthy_software.result.Result;
import com.healthy_software.service.GoalService;
import com.healthy_software.vo.GoalVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class GoalServiceImpl implements GoalService {
    @Resource
    private GoalMapper goalMapper;

    @Resource
    private GoalDetailsMapper goalDetailsMapper;

    @Override
    public Result<GoalVO> getGoal(Long userId) {
        List<Goal> goals = goalMapper.getGoalsByUser(userId);

        List<GoalDetail> goalDetails = new ArrayList<>();
        for(Goal goal : goals) {
            int goalId = goal.getId();
            goalDetails.add(goalDetailsMapper.getGoalsDetailsByGoal(goalId));
        }

        GoalVO goalVO = GoalVO.builder().goalDetails(goalDetails).goal(goals).build();
        return Result.ok(MessageConstant.GOAL_GET_SUCCESS ,goalVO);
    }

    @Override
    public Result<Integer> setGoal(Long userId, SetGoalRequestDTO setGoalRequestDTO) {
        GoalDTO goalDTO = setGoalRequestDTO.getGoalDTO();
        GoalDetailDTO goalDetailDTO = setGoalRequestDTO.getGoalDetailDTO();

        if (goalDTO == null || goalDetailDTO == null) {
            return Result.fail(MessageConstant.GOAL_NULL);
        }

        Goal goal = new Goal();
        BeanUtils.copyProperties(goalDTO, goal);
        goal.setUserId(Math.toIntExact(userId));
        goalMapper.insert(goal);


        Long goalId = (long) goal.getId();
        GoalDetail goalDetail = new GoalDetail();
        BeanUtils.copyProperties(goalDetailDTO, goalDetail);
        goalDetail.setGoalId(Math.toIntExact(goalId));

        goalDetailsMapper.insert(goalDetail);

        return Result.ok(MessageConstant.GOAL_SET_SUCCESS,goalId.intValue());
    }

}
